/*
 * This code is licensed under the Apache License 2.0.
 * Read more at http://blippit.googlecode.com/
 */
package com.googlecode.blippit;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

public class SongListViewAdapter extends ArrayAdapter<BlipApi.Song> {
	public SongListViewAdapter(Context context, int resource,
			int textViewResourceId, BlipApi.Song[] objects) {
		super(context, resource, textViewResourceId, objects);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final View v = super.getView(position, convertView, parent);
		final BlipApi.Song song = getItem(position);
		final Activity activity = (Activity)getContext();
		
		StringBuffer songArtist = new StringBuffer(song.artist());
		if (song instanceof BlipApi.Blip) {
			// Put the title in there too
			if (songArtist.length() > 0)
				songArtist.insert(0, " - ");
			songArtist.insert(0, song.title());
		}
		
		v.setTag(song);
		TextView artist = (TextView)v.findViewById(R.id.song_list_artist);
		TextView location = (TextView)v.findViewById(R.id.song_list_location);
		ImageButton menu = (ImageButton)v.findViewById(R.id.song_list_menu);
		ImageButton play = (ImageButton)v.findViewById(R.id.song_list_play);

		artist.setText(songArtist);
		activity.registerForContextMenu(v);

		if (song.type().equals(BlipApi.FUZZ_SONG)) {
			location.setText("fuzz.com");
			// Don't know how to play these; needs some magic URL trickery
			play.setVisibility(Button.INVISIBLE);
		} else {
			final Uri uri = Uri.parse(song.url());
			location.setText(uri.getHost());
			play.setVisibility(Button.VISIBLE);
			play.setOnClickListener(new OnClickListener() {
				public void onClick(View button) {
					Intent i = new Intent();
					i.setAction(Intent.ACTION_VIEW);
					i.setData(uri);
					i.putExtra("artist", song.artist());  // TODO: make this work
					i.putExtra("track", song.title());  // TODO: make this work
					i.setComponent(new ComponentName("com.android.music", "com.android.music.StreamStarter"));
					activity.startActivity(i);
				}
			});
		}
		menu.setVisibility(Button.VISIBLE);
		menu.setOnClickListener(new OnClickListener() {
			public void onClick(View button) {
				activity.openContextMenu(v);
			}
		});
		
		return v;
	}

}
